package com.sshe.web.action.util;

import java.io.IOException;
import java.io.PrintWriter;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import net.sf.json.JSONSerializer;
import net.sf.json.JsonConfig;

import org.apache.struts2.ServletActionContext;

import com.opensymphony.xwork2.ActionSupport;

/**
 * Action辅助工具类<br/>
 * 
 * @author 罗超(455723382@qq.com)<br/>
 *         2013-8-2 下午03:02:11
 */
public class ActionUtil extends ActionSupport {

	private static final long serialVersionUID = 1482543991033134648L;

	private HttpServletResponse response;
	private HttpServletRequest request;

	public HttpServletResponse getResponse() {
		response = ServletActionContext.getResponse();
		return response;
	}

	public HttpServletRequest getRequest() {
		request = ServletActionContext.getRequest();
		return request;
	}

	/**
	 * 输出JsonResult对象<br/>
	 * 
	 * @param jsonResult
	 */
	public void writer(JsonResult jsonResult) {
		HttpServletResponse response = getResponse();
		response.setContentType("text/html;charset=UTF-8");
		response.addHeader("Content-Type", "text/html;charset=UTF-8");
		response.setHeader("Pragma", "No-cache");
		response.setHeader("Cache-Control", "no-cache");
		response.setDateHeader("Expires", 0L);
		try {
			PrintWriter out = response.getWriter();
			out.println(JSONSerializer.toJSON(jsonResult));
			out.flush();
			out.close();
		} catch (IOException e) {
			e.printStackTrace();
		}
	}

	/**
	 * 输出Json对象<br/>
	 * 
	 * @param object
	 */
	public void writer(Object object) {
		HttpServletResponse response = getResponse();
		response.setContentType("text/html;charset=UTF-8");
		response.addHeader("Content-Type", "text/html;charset=UTF-8");
		response.setHeader("Pragma", "No-cache");
		response.setHeader("Cache-Control", "no-cache");
		response.setDateHeader("Expires", 0L);
		try {
			PrintWriter out = response.getWriter();
			JsonConfig config = new JsonConfig();
			config.registerJsonValueProcessor(java.util.Date.class,
					new DateJsonValueProcessor("yyyy-MM-dd hh:mm:ss"));
			out.println(JSONSerializer.toJSON(object, config));
			out.flush();
			out.close();
		} catch (IOException e) {
			e.printStackTrace();
		}
	}

	/**
	 * 输出字符串<br/>
	 * 
	 * @param string
	 */
	public void writer(String string) {
		HttpServletResponse response = getResponse();
		response.setContentType("text/html;charset=UTF-8");
		response.addHeader("Content-Type", "text/html;charset=UTF-8");
		response.setHeader("Pragma", "No-cache");
		response.setHeader("Cache-Control", "no-cache");
		response.setDateHeader("Expires", 0L);
		try {
			PrintWriter out = response.getWriter();
			out.println(string);
			out.flush();
			out.close();
		} catch (IOException e) {
			e.printStackTrace();
		}
	}

}
